package com.cskaoyan.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @Author tangjian
 * @Date 2021/10/21 16:29
 * @description Realms 中选择对应的Realm
 */
public class CustomAuthenticator extends ModularRealmAuthenticator {

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        Collection<Realm> originRealm = this.getRealms();

        //根据MallToken的type 类型去选择对应的realm
        MallToken mallToken = (MallToken) authenticationToken;
        String type = mallToken.getType();
        ArrayList<Realm> realms = new ArrayList<>();
        for (Realm realm : originRealm) {
            if (realm.getName().toLowerCase().contains(type.toLowerCase())){
                realms.add(realm);
            }
        }

        return realms.size() == 1 ? this.doSingleRealmAuthentication((Realm)realms.iterator().next(), authenticationToken) : this.doMultiRealmAuthentication(realms, authenticationToken);
    }
}
